<template>
  <div class="login-container">
    <!-- model 用于收集表单的数据 rules 表单严重规则 -->
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on"
      label-position="left">

      <div class="title-container">
        <h3 class="title" v-if="adv == 0">遇识爱后台管理系统</h3>
        <h3 class="title" v-else>遇识爱代理商管理系统</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input ref="username" v-model="loginForm.username" placeholder="用户名" name="username" type="text" tabindex="1"
          auto-complete="on" />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType" placeholder="密码"
          name="password" tabindex="2" auto-complete="on" @keyup.enter.native="handleLogin" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <div style="display:flex;justify-content: space-between;" v-if="adv == 0">
        <el-form-item prop="number">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input ref="imageCode " v-model="loginForm.imageCode" placeholder="验证码" name="imageCode" type="text"
            tabindex="3" auto-complete="on" />
        </el-form-item>
        <img :src="imageBase64" style="width:140px;height:50px" @click="getImageCodes" />
      </div>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;"
        @click.native.prevent="handleLogin">登录</el-button>

      <div class="tips">
        <span style="margin-right:20px;">遇识爱</span>
        <span> 欢迎您</span>
      </div>

    </el-form>
  </div>
</template>

<script>
import {
  resetRouter,
  constantRoutes
} from '@/router'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  validUsername
} from '@/utils/validate'
import {
  getImageCode,
  login
} from '@/api/user'
export default {
  name: 'Login',
  mounted() {
    if (this.adv == 0) {
      this.getImageCodes()
    }
  },
  data() {
    // 验证用户名和密码操作
    const validateUsername = (rule, value, callback) => {
      if (value.length < 2) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 3) {
        callback(new Error('请输入正确的登录密码'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        imageCode: '',
        imageToken: ''
      },
      loginRules: {
        username: [{
          required: true,
          trigger: 'blur',
          validator: validateUsername
        }],
        password: [{
          required: true,
          trigger: 'blur',
          validator: validatePassword
        }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      imageBase64: '',
      adv: 0,

      permissionArr1: [{
        "componentName": "AdvertiserIndex",
        "createTime": "2024-01-06 11:01:16",
        "createUserId": null,
        "icon": "",
        "id": 66,
        "path": "",
        "permCode": "",
        "permName": "广告商管理",
        "pid": 0,
        "rankId": null,
        "type": 1,
        "updateTime": null
      },
      {
        "componentName": "AdvertiserIndex",
        "createTime": "2024-01-06 11:02:11",
        "createUserId": null,
        "icon": "",
        "id": 67,
        "path": "",
        "permCode": "",
        "permName": "广告数据",
        "pid": 66,
        "rankId": null,
        "type": 1,
        "updateTime": null
      },
      {
        "componentName": "Advertisers",
        "createTime": "2024-01-06 11:02:29",
        "createUserId": null,
        "icon": "",
        "id": 68,
        "path": "",
        "permCode": "",
        "permName": "广告主",
        "pid": 66,
        "rankId": null,
        "type": 1,
        "updateTime": null
      },
      // {
      //   "componentName": "AdvDesign",
      //   "createTime": "2024-01-06 11:02:42",
      //   "createUserId": null,
      //   "icon": "",
      //   "id": 69,
      //   "path": "",
      //   "permCode": "",
      //   "permName": "广告设计投放",
      //   "pid": 66,
      //   "rankId": null,
      //   "type": 1,
      //   "updateTime": null
      // },
      // {
      //   "componentName": "AdvDetails",
      //   "createTime": "2024-01-06 11:02:58",
      //   "createUserId": null,
      //   "icon": "",
      //   "id": 70,
      //   "path": "",
      //   "permCode": "",
      //   "permName": "广告详情",
      //   "pid": 66,
      //   "rankId": null,
      //   "type": 1,
      //   "updateTime": null
      // },
      {
        "componentName": "AdvertiserInformation",
        "createTime": "2024-01-06 11:03:32",
        "createUserId": null,
        "icon": "",
        "id": 72,
        "path": "",
        "permCode": "",
        "permName": "代理商资料",
        "pid": 66,
        "rankId": null,
        "type": 1,
        "updateTime": null
      },
      {
        "componentName": "AdvEarnings",
        "createTime": "2024-01-06 11:03:15",
        "createUserId": null,
        "icon": "",
        "id": 71,
        "path": "",
        "permCode": "",
        "permName": "我的收益",
        "pid": 66,
        "rankId": null,
        "type": 1,
        "updateTime": null
      },

        // {
        //   "componentName": "SubordinateAgents",
        //   "createTime": "2024-01-25 15:18:39",
        //   "createUserId": null,
        //   "icon": "",
        //   "id": 78,
        //   "path": "",
        //   "permCode": "",
        //   "permName": "下级代理商管理",
        //   "pid": 66,
        //   "rankId": null,
        //   "type": 1,
        //   "updateTime": null
        // },
        // {
        //   "componentName": "WithdrawalAdvertiser",
        //   "createTime": "2024-02-06 14:55:56",
        //   "createUserId": null,
        //   "icon": "",
        //   "id": 82,
        //   "path": "",
        //   "permCode": "",
        //   "permName": "提现进度",
        //   "pid": 66,
        //   "rankId": null,
        //   "type": 1,
        //   "updateTime": null
        // }
      ],
      permissionArr2: [{
        "componentName": "AdvertiserIndex",
        "createTime": "2024-01-06 11:01:16",
        "createUserId": null,
        "icon": "",
        "id": 66,
        "path": "",
        "permCode": "",
        "permName": "广告商管理",
        "pid": 0,
        "rankId": null,
        "type": 1,
        "updateTime": null
      },
      {
        "componentName": "AdvertiserIndex",
        "createTime": "2024-01-06 11:02:11",
        "createUserId": null,
        "icon": "",
        "id": 67,
        "path": "",
        "permCode": "",
        "permName": "广告数据",
        "pid": 66,
        "rankId": null,
        "type": 1,
        "updateTime": null
      },
      // {
      //   "componentName": "Advertisers",
      //   "createTime": "2024-01-06 11:02:29",
      //   "createUserId": null,
      //   "icon": "",
      //   "id": 68,
      //   "path": "",
      //   "permCode": "",
      //   "permName": "广告主",
      //   "pid": 66,
      //   "rankId": null,
      //   "type": 1,
      //   "updateTime": null
      // },
      // {
      //   "componentName": "AdvDesign",
      //   "createTime": "2024-01-06 11:02:42",
      //   "createUserId": null,
      //   "icon": "",
      //   "id": 69,
      //   "path": "",
      //   "permCode": "",
      //   "permName": "广告设计投放",
      //   "pid": 66,
      //   "rankId": null,
      //   "type": 1,
      //   "updateTime": null
      // },
      // {
      //   "componentName": "AdvDetails",
      //   "createTime": "2024-01-06 11:02:58",
      //   "createUserId": null,
      //   "icon": "",
      //   "id": 70,
      //   "path": "",
      //   "permCode": "",
      //   "permName": "广告详情",
      //   "pid": 66,
      //   "rankId": null,
      //   "type": 1,
      //   "updateTime": null
      // },
      {
        "componentName": "AdvertiserInformation",
        "createTime": "2024-01-06 11:03:32",
        "createUserId": null,
        "icon": "",
        "id": 72,
        "path": "",
        "permCode": "",
        "permName": "代理商资料",
        "pid": 66,
        "rankId": null,
        "type": 1,
        "updateTime": null
      },
      {
        "componentName": "AdvEarnings",
        "createTime": "2024-01-06 11:03:15",
        "createUserId": null,
        "icon": "",
        "id": 71,
        "path": "",
        "permCode": "",
        "permName": "我的收益",
        "pid": 66,
        "rankId": null,
        "type": 1,
        "updateTime": null
      },
        // {
        //   "componentName": "WithdrawalAdvertiser",
        //   "createTime": "2024-02-06 14:55:56",
        //   "createUserId": null,
        //   "icon": "",
        //   "id": 82,
        //   "path": "",
        //   "permCode": "",
        //   "permName": "提现进度",
        //   "pid": 66,
        //   "rankId": null,
        //   "type": 1,
        //   "updateTime": null
        // }
      ],
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        console.log('@@@@@@@@@@@@@@@@@@@@@', route)
        this.adv = route.query.adv || 0
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },

  methods: {
    // 两个路由数组进行对比，对比显示当前用户该显示的路由权限
    computedAsyncRouters(constantRoutes, routers) {
      let newArr = routers.map(item => {
        return item.componentName;
      })
      return constantRoutes.filter(item => {
        if (newArr.indexOf(item.name) != -1) {
          if (item.children && item.children.length) {
            item.children = this.computedAsyncRouters(item.children, routers)
          }
          return true;
        }
      })
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    async getImageCodes() {
      let res = await getImageCode()
      this.imageBase64 = res.data.imageBase64;
      this.loginForm.imageToken = res.data.imageToken;
      console.log(res, "139");
    },

    async getAdvertisementUserMes(advertisementUserId) {
      // this.$axios({
      //   method: 'post',
      //   url: this.$baseURL + '/biz/advertisementUser/getAdvertisementUserMes',
      //   headers: {
      //     'session_token': localStorage.getItem('adv_session_token')
      //   }
      // }).then((response) => {
      //   console.log(response.data)
      // }).catch((error) => {
      //   console.log(error) //请求失败返回的数据
      // })
      let res = await this.$API.members.getAdvertisementUserMes({
        advertisementUserId
      })
      console.log('代理商信息', res)
      localStorage.setItem('advertisementUserMes', JSON.stringify(res.data))
      if (res.data.level == 1) {
        var permissionList = this.permissionArr1
      } else {
        var permissionList = this.permissionArr2
      }
      localStorage.setItem('permissionArr', JSON.stringify(permissionList))
      let treesId = permissionList.map(item => {
        return item.componentName;
      })
      this.$store.commit('user/SET_PERMISSIONLIST', permissionList)
      this.$store.commit('user/SET_TREESID', treesId)
      this.$store.commit('user/SET_RESULTASYNCROUTER', this.computedAsyncRouters(constantRoutes,
        permissionList))

      this.$router.replace({
        name: 'AdvertiserIndex'
      })

      // location.reload([false])
      // history.go(0)
    },

    // 登录请求
    handleLogin() {
      //验证规则
      if (this.adv == 0) {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true
            console.log(this.loginForm, 'zheshi')
            // 派发一个action:user/login，带着用户名与密码的载荷
            this.$store.dispatch('user/login', this.loginForm).then(() => {
              // localStorage.setItem('adv_session_token', this.$store.getters.token)
              this.$router.push({
                path: this.redirect || '/'
              })
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
        // console.log(this.$store.getters.token, 'token');
      } else {
        console.log(this.loginForm)
        if (this.loginForm.password == '' || this.loginForm.userName == '') {
          this.$message.info("请填写账号密码");
          return;
        }
        this.$axios({
          method: 'post',
          url: this.$baseURL + '/biz/advertisementUser/advertisementUserLogin',
          data: {
            password: this.loginForm.password,
            userName: this.loginForm.username
          }
        }).then((response) => {
          console.log('代理商', response.data) //请求成功返回的数据
          if (response.data.code == 200) {
            setToken(response.data.data.sessionToken)
            localStorage.setItem('adv_session_token', response.data.data.sessionToken)
            localStorage.setItem('adv_userName', response.data.data.userName)
            let userRole = '广告代理商'
            this.$store.commit('user/SET_USERROLE', userRole)
            this.$store.commit('user/SET_TOKEN', response.data.data.sessionToken)
            this.$store.commit('user/SET_NAME', response.data.data.userName)

            this.getAdvertisementUserMes(response.data.data.advertisementUserId)
          } else {
            this.$message.error(response.data.msg)
          }
        }).catch((error) => {
          console.log(error) //请求失败返回的数据
          this.$message.error(error)
        })
        // let res = this.$API.members.advertisementUserLogin({
        //   password: this.loginForm.password,
        //   userName: this.loginForm.username
        // });
        // console.log(res)
        // if (res.code == 200) {
        // let permissionList = [{
        //     "componentName": "AdvertiserIndex",
        //     "createTime": "2024-01-06 11:01:16",
        //     "createUserId": null,
        //     "icon": "",
        //     "id": 66,
        //     "path": "",
        //     "permCode": "",
        //     "permName": "广告商管理",
        //     "pid": 0,
        //     "rankId": null,
        //     "type": 1,
        //     "updateTime": null
        //   },
        //   {
        //     "componentName": "AdvertiserIndex",
        //     "createTime": "2024-01-06 11:02:11",
        //     "createUserId": null,
        //     "icon": "",
        //     "id": 67,
        //     "path": "",
        //     "permCode": "",
        //     "permName": "广告数据",
        //     "pid": 66,
        //     "rankId": null,
        //     "type": 1,
        //     "updateTime": null
        //   },
        //   {
        //     "componentName": "Advertisers",
        //     "createTime": "2024-01-06 11:02:29",
        //     "createUserId": null,
        //     "icon": "",
        //     "id": 68,
        //     "path": "",
        //     "permCode": "",
        //     "permName": "广告主",
        //     "pid": 66,
        //     "rankId": null,
        //     "type": 1,
        //     "updateTime": null
        //   },
        //   {
        //     "componentName": "AdvDesign",
        //     "createTime": "2024-01-06 11:02:42",
        //     "createUserId": null,
        //     "icon": "",
        //     "id": 69,
        //     "path": "",
        //     "permCode": "",
        //     "permName": "广告设计投放",
        //     "pid": 66,
        //     "rankId": null,
        //     "type": 1,
        //     "updateTime": null
        //   },
        //   {
        //     "componentName": "AdvDetails",
        //     "createTime": "2024-01-06 11:02:58",
        //     "createUserId": null,
        //     "icon": "",
        //     "id": 70,
        //     "path": "",
        //     "permCode": "",
        //     "permName": "广告详情",
        //     "pid": 66,
        //     "rankId": null,
        //     "type": 1,
        //     "updateTime": null
        //   },
        //   {
        //     "componentName": "AdvEarnings",
        //     "createTime": "2024-01-06 11:03:15",
        //     "createUserId": null,
        //     "icon": "",
        //     "id": 71,
        //     "path": "",
        //     "permCode": "",
        //     "permName": "我的收益",
        //     "pid": 66,
        //     "rankId": null,
        //     "type": 1,
        //     "updateTime": null
        //   },
        //   {
        //     "componentName": "AdvertiserInformation",
        //     "createTime": "2024-01-06 11:03:32",
        //     "createUserId": null,
        //     "icon": "",
        //     "id": 72,
        //     "path": "",
        //     "permCode": "",
        //     "permName": "代理商资料",
        //     "pid": 66,
        //     "rankId": null,
        //     "type": 1,
        //     "updateTime": null
        //   }
        // ]
        //   let treesId = permissionList.map(item => {
        //     return item.componentName;
        //   })
        //   // console.log(data)
        //   commit('SET_NAME', name)
        //   commit('SET_AVATAR', headimgurl)
        //   commit('SET_USERROLE', userRole)
        //   commit('SET_PERMISSIONLIST', permissionList)
        //   commit('SET_TREESID', treesId)
        //   commit('SET_RESULTASYNCROUTER', computedAsyncRouters(constantRoutes, permissionList))
        //   this.$store.commit('SET_USERROLE', userRole)
        //   }
      }

    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
